﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Aop_IOCService.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using AspectCore.Extensions.DependencyInjection;
using RestTemplateCore;


namespace Aop_IOCService
{
    //Install-Package AspectCore.Extensions.DependencyInjection
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            // services.AddSingleton<Person>();
            RegisterServices(this.GetType().Assembly, services);
            return services.BuildAspectCoreServiceProvider();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }

        private static void RegisterServices(Assembly asm, IServiceCollection services)
        {
            //遍历程序集中的所有 public 类型
            foreach (Type type in asm.GetExportedTypes())
            {
                //判断类中是否有标注了 CustomInterceptorAttribute 的方法
                if (type.GetMethods().Any(m => m.GetCustomAttribute(typeof(MySelfHystrixCoreAttribute)) != null))
                {
                    services.AddSingleton(type);
                }
            }
        }

    }
}
